﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VTLive.Models;


namespace VTLive.Controllers
{
    public class StationController : BaseController
    {
        //StationController heldur utan um CRUD-virkni fyrir stöðvar
        //hluti.


        //Fallið birtir síðu með upplýsingum um stjórnunarmöguleika
        //ákveðinnar stöðvar.
        public ActionResult Manage(int id)
        {
            StationRepository SRep = new StationRepository();

            if (m_iUserID != SRep.GetStation(id).OwnerID) return View("BadAccess");                
                    
            StationManagementModel SMM = new StationManagementModel();
            Station Station = SRep.GetStation(id);
            SMM.station = Station;
            ScheduleRepository ScRep = new ScheduleRepository();
            SMM.schedules = ScRep.GetAllSchedulesOfStation(Station.ID);
            return View(SMM);
        }


        //Fallið birtir upplýsingar um ákveðna stöð.
        public ActionResult Details(int id)
        {
            UserRepository URep = new UserRepository();
            AssociateRepository ARep = new AssociateRepository();
            ScheduleRepository SRep = new ScheduleRepository();
            EpisodeRepository ERep = new EpisodeRepository();
            VideoRepository VRep = new VideoRepository();
            StationRepository StRep = new StationRepository();
            
            var Station = StRep.GetStation(id);
            ViewData["station_name"] = Station.Name;
            ViewData["station_description"] = Station.Description;
            ViewData["station_owner"] = URep.GetUser(Station.OwnerID).Username;
            //ViewData["station_associates"] = ARep.GetAllAssociatesByStation(id);
            var StationSchedule = SRep.GetCurrentScheduleOfStation(id);
            IQueryable<Episode> Episodes = null;
            try
            {
                Episodes = ERep.GetAllEpisodesOfSchedule(StationSchedule.ID);
            }
            catch (NullReferenceException)
            { }


            //Hér er búinn til strengur úr VideoID-um þar sem þau eru aðskild með 
            //"tilde" ~ merkinu, þessi strengur er til þess að hægt sé að segja
            //JavaScript forritunarviðmóti spilarans hver dagskráin er.

            var Videos = VRep.GetAllVideosOfSchedule(StationSchedule.ID);
            String VidString = null;
            bool bIsFirst = true;
            foreach (Video vid in Videos)
            {
                if (bIsFirst)
                {
                    VidString = vid.Link;
                    bIsFirst = false;
                    continue;
                }
                VidString = VidString + "~" + vid.Link;
            }

            ViewData["station_video_string"] = VidString;
            if(StationSchedule != null) ViewData["station_schedule"] = VRep.GetAllVideosOfSchedule(StationSchedule.ID);

            return View();
        }

        //Fallið skilar View-i sem gefur innskráðum notenda færi á að búa til stöð
        [HttpGet]
        public ActionResult CreateStation()
        {
            if (Session["user_id"] == null) return View("BadAccess");
            Station Station = new Station();
            Station.OwnerID = int.Parse(Session["user_id"].ToString());
            return View("Create", Station);
        }


        //Fallið tekur við upplýsingum um nýja stöð og býr hana til
        [HttpPost]
        public ActionResult CreateStation(FormCollection coll)
        {
            StationRepository SRep = new StationRepository();
            UserRepository urep = new UserRepository();
            Station Station = new Station();
            Station.OwnerID = int.Parse(Session["user_id"].ToString());
            Station.Type = Request.Form["Type"];
            Station.Name = Request.Form["Name"];
            Station.Description = Request.Form["Description"];
            Station NewStation = SRep.InsertAndGetNewStation(Station);

            return RedirectToAction("Manage", "Station", new {id = NewStation.ID });
        }


        //Fallið skilar View-i sem gefur eiganda stöðvar færi
        //á aðilum við stöð sína.
        [HttpGet]
        public ActionResult Associations(int id)
        {
            StationRepository SRep = new StationRepository();
            {
                if (m_iUserID == SRep.GetStation(id).OwnerID) return View(new NewAssociateViewModel());
                else return View("BadAccess");
            }
        }


        //Fallið tekur inn upplýsingar um nýjan aðila að stöð og bætir honum við.
        [HttpPost]
        public ActionResult Associations(int id, FormCollection collection)
        { 
            AssociateRepository ARep = new AssociateRepository();
            UserRepository URep = new UserRepository();
            StationRepository SRep = new StationRepository();

            if (Session["user_id"] != null && SRep.IsOwnerOf(Session["user_id"] as int?, id))
            {
                Associate Associate = new Associate();

                var UsrNm = Request.Form["Username"];
                User AssociateUser = URep.GetUserByUserName(UsrNm);
                if (AssociateUser != null)
                {
                    Associate.StationID = id;
                    Associate.UserID = AssociateUser.ID;
                    ARep.Add(Associate);
                    ARep.Save();
                }

                return RedirectToAction("Manage", "Station", new { id = id });
            }
            else
            {
                return View("BadAcces");            
            }
        }
    }
}
